﻿#include "rowhovertableview.h"

#include <QDebug>
#include <QPainter>

RowHoverDelegate::RowHoverDelegate(QObject *parent) : QStyledItemDelegate(parent),
    m_hovered_row(-1)
{
}

bool RowHoverDelegate::setHoverRow(int row)
{
    if (row != m_hovered_row)
    {
        m_hovered_row = row;
        return true;
    }
    return false;
}

int RowHoverDelegate::getHoverRow()
{
    return m_hovered_row;
}

void RowHoverDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                             const QModelIndex &index) const
{
    QStyleOptionViewItemV4 opt(option);
    opt.state &= ~QStyle::State_HasFocus;
    if (index.row() == m_hovered_row)
    {
        opt.state |= QStyle::State_MouseOver;
    }
    else
    {
        opt.state &= ~QStyle::State_MouseOver;
    }
    QStyledItemDelegate::paint(painter, opt, index);
}
/******************************************************************************/
RowHoverTableView::RowHoverTableView(QWidget *parent) :
    QTableView(parent)
{
    setMouseTracking(true);
    setSelectionBehavior(SelectRows);

    RowHoverDelegate *delegate = new RowHoverDelegate(this);
    this->setItemDelegate(delegate);
}

void RowHoverTableView::mouseMoveEvent(QMouseEvent *event)
{
    QTableView::mouseMoveEvent(event);

    RowHoverDelegate *delegate = qobject_cast<RowHoverDelegate*>(this->itemDelegate());
    if (delegate)
    {
        QModelIndex index = indexAt(event->pos());
        if (delegate->setHoverRow(index.row()))
        {
            for (int col = 0; col < model()->columnCount(); ++col)
            {
                if (col == index.column())
                {
                    continue;
                }
                update(model()->index(index.row(), col));
            }
        }
    }
}

void RowHoverTableView::leaveEvent(QEvent *event)
{
    QTableView::leaveEvent(event);

    RowHoverDelegate *delegate = qobject_cast<RowHoverDelegate*>(this->itemDelegate());
    if (delegate)
    {
        int last_hover_row = delegate->getHoverRow();
        if (last_hover_row >= 0)
        {
            delegate->setHoverRow(-1);
            for (int col = 0; col < model()->columnCount(); ++col)
            {
                update(model()->index(last_hover_row, col));
            }
        }
    }
}

void RowHoverTableView::wheelEvent(QWheelEvent *event)
{
    QTableView::wheelEvent(event);

    RowHoverDelegate *delegate = qobject_cast<RowHoverDelegate*>(this->itemDelegate());
    if (delegate)
    {
        QModelIndex index = indexAt(event->pos());
        if (delegate->setHoverRow(index.row()))
        {
            for (int col = 0; col < model()->columnCount(); ++col)
            {
                if (col == index.column())
                {
                    continue;
                }
                update(model()->index(index.row(), col));
            }
        }
    }
}
